package javaer.starter.idea.util.sql;


import javaer.starter.idea.util.ThreadUtils;
import javaer.starter.idea.window.component.ProgressComponent;
import javaer.starter.model.BaseModel;
import javaer.starter.placeholder.ParameterMapping;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;
import java.util.TreeSet;

import static javaer.starter.JavaerStarter.CONFIG_DIRECTORY;
import static javaer.starter.JavaerStarter.JAVAER_STARTER_TEMPLATE;
import static javaer.starter.JavaerStarter.SQL_DIRECTORY;

/**
 * @author yangzhen
 * @date 2021/11/30 22:19
 * @since 1.0.0
 */
public class FileRenderUtils {

    public static final String line_separator = System.lineSeparator();

    public static String getSqlValue(BaseModel model, int index, int maxIndex) {
        StringBuilder sb = new StringBuilder(model.getSql());
        if (index < maxIndex - 1) {
            sb.append(",");
        } else {
            sb.append(";");
        }
        return sb.toString();
    }

    public static void generateSqlFile(Path directory, String filename, String sqlTemplate, Set<? extends BaseModel> models) throws IOException {
        if (models == null || models.isEmpty()) {
            return;
        }
        Path filepath = directory.resolve(JAVAER_STARTER_TEMPLATE).resolve(SQL_DIRECTORY).resolve(filename);
        createFileIfNotExists(filepath);
        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filepath.toFile()))) {
            bufferedWriter.write(sqlTemplate);
            int index = 0;
            for (BaseModel model : models) {
                String sql = getSqlValue(model, index, models.size());
                bufferedWriter.write(sql);
                bufferedWriter.write(line_separator);
                index++;
            }
        }
    }

    public static void generateSqlFile(Path directory, String filename, String sqlTemplate, Set<? extends BaseModel> models, ProgressComponent progressComponent) throws IOException {
        if (models == null || models.isEmpty()) {
            return;
        }
        Path filepath = directory.resolve(JAVAER_STARTER_TEMPLATE).resolve(SQL_DIRECTORY).resolve(filename);
        createFileIfNotExists(filepath);
        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filepath.toFile()))) {
            bufferedWriter.write(sqlTemplate);
            int index = 0;
            for (BaseModel model : models) {
                progressComponent.current = index + 1;
                ThreadUtils.sleepMs(50);
                String sql = getSqlValue(model, index, models.size());
                bufferedWriter.write(sql);
                bufferedWriter.write(line_separator);
                index++;
            }
        }
    }

    public static void generateConfigFile(Path directory, String filename, Set<ParameterMapping> parameterMappings) throws IOException {
        if (parameterMappings != null && !parameterMappings.isEmpty()) {
            TreeSet<ParameterMapping> sortedParameterMapping = new TreeSet<>(parameterMappings);
            Path resolve = directory.resolve(JAVAER_STARTER_TEMPLATE).resolve(CONFIG_DIRECTORY).resolve(filename);
            createFileIfNotExists(resolve);
            try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resolve.toFile()))) {
                for (ParameterMapping parameterMapping : sortedParameterMapping) {
                    String content = dealParameter(parameterMapping.getContent());
                    if (content != null) {
                        bufferedWriter.write(content);
                        bufferedWriter.write(line_separator);
                    }
                }
            }
        }
    }

    public static String dealParameter(String content) {
        if (content == null || "".equals(content.trim())) {
            return null;
        }
        if (content.contains(":")) {
            int index = content.indexOf(":");
            content = content.substring(0, index) + "=" + content.substring(index + 1);
            return content;
        } else {
            return content + "=";
        }
    }

    public static void createDirsIfNotExists(Path path) throws IOException {
        if (path == null) {
            return;
        }
        if (!Files.exists(path)) {
            Files.createDirectories(path);
        }
    }

    public static void createFileIfNotExists(Path path) throws IOException {
        if (!Files.exists(path)) {
            createDirsIfNotExists(path.getParent());
            Files.createFile(path);
        }
    }
}
